// content.js
// 监听来自扩展程序的消息
// alert("这里是 content.js")
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    alert("监听到的消息了")
    if (request.action === 'getTd2Data') {
        alert("监听到的消息 getTd2Data 了")
        var td2Data = document.querySelector("#2").innerHTML;

        sendResponse({ td2Data: td2Data });
    }
});



//////////////////////////////////////////////////////////////// 添加提交按钮 start ////////////////////////////////////////////////////////////////
const style = document.createElement('style');
style.textContent = `
    .btn-group {
        display: flex;
        justify-content: center;
        margin: 5px 0; /* 根据需要调整间距 */
    }
    .btn-warning{
        color: #fff;
        background-color: #fb3b71;
        padding: 12px 27px;
    }
`;
document.head.appendChild(style);
const targetElement = document.querySelector('#wrapper > div.wrapper__holder > main'); // 替换为目标元素的选择器
if (targetElement) {
    // content.js
    const btnGroup = document.createElement('div');
    btnGroup.className = 'btn-group';
    btnGroup.setAttribute('role', 'group');
    btnGroup.setAttribute('aria-label', 'Basic example');

    // 创建按钮
    const buttons = [
        { id: 'pollfish_submit_10', text: '10秒', time: 10, class: 'btn-primary'},
        { id: 'pollfish_submit_20', text: '20秒', time: 20, class: 'btn-primary'},
        { id: 'pollfish_submit_30', text: '30秒', time: 30, class: 'btn-primary'},
        { id: 'pollfish_submit_60', text: '60秒', time: 60, class: 'btn-primary'},
    ];

    buttons.forEach(btn => {
        const button = document.createElement('button');
        button.id = btn.id;
        button.type = 'button';
        button.className = `btn ${btn.class}`;
        button.textContent = btn.text;

        // 添加点击事件
        button.addEventListener('click', function () {
            countdownScript(btn.time); // 调用 countdownScript 函数
        });

        btnGroup.appendChild(button);
    });
    targetElement.parentNode.insertBefore(btnGroup, targetElement);
}

// content.js
window.countdownScript = function (timeLeft) {
    var element = document.getElementById("take-survey-btn");
    if (!element) {
        var element = document.getElementById("submit-btn");
    }

    let countdown = timeLeft;
    const intervalId = setInterval(() => {
        countdown--;
        element.textContent = countdown + "秒后提交";
        if (countdown <= 0) {
            clearInterval(intervalId);
            element.textContent = "正在提交";
            element.click();
            element.click()
        }
    }, 1000);
};

//////////////////////////////////////////////////////////////// 添加提交按钮 end ////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////// 添加随机按钮 start ////////////////////////////////////////////////////////////////
if (targetElement) {
    // content.js
    const random_btnGroup = document.createElement('div');
    random_btnGroup.className = 'btn-group';
    random_btnGroup.setAttribute('role', 'group');
    random_btnGroup.setAttribute('aria-label', 'Basic example');

    // 创建按钮
    const random_buttons = [
        { id: 'pollfish_random_order'   , text: '随机排名', time: 3, class: 'btn-warning'},
        { id: 'pollfish_random_radio'   , text: '随机单选', time: 3, class: 'btn-warning'},
        { id: 'pollfish_random_checkbox', text: '随机多选', time: 3, class: 'btn-warning'}
    ];

    random_buttons.forEach(btn => {
        const button = document.createElement('button');
        button.id = btn.id;
        button.type = 'button';
        button.className = `btn ${btn.class}`;
        button.textContent = btn.text;

        // 添加点击事件
        button.addEventListener('click', function () {
            pollfish_random_select(btn.id, btn.time, btn.text); // 调用 pollfish_random_select 函数
        });

        random_btnGroup.appendChild(button);
    });
    targetElement.parentNode.insertBefore(random_btnGroup, targetElement);
}

// pollfish 随机选择
window.pollfish_random_select = function (btn_id, timeLeft, text) {
    let btn = document.getElementById(btn_id);
    // alert(text)
    if (text == "随机单选") {
        console.log("随机单选")
        let elements = document.querySelectorAll('.matrix.clearfix.answerMatrix'); // 先判断是否是多组单选
        if (elements && elements.length > 0) {
            console.log("随机多组单选")
            let index = 0;
            let countdown = timeLeft;
            let intervalId = setInterval(() => {
                countdown--;
                // btn.textContent = countdown + "秒后选中";
                btn.textContent = "第" + (index + 1) + "/" + elements.length + "在" + countdown + "秒后选中";
                if (index < elements.length && countdown <= 0) {
                    let labels = elements[index].querySelectorAll('.matrix__answer.answer--single-choice'); // 每组中的（单选）
                    let selectedIndex = Math.floor(Math.random() * labels.length);
                    labels[selectedIndex].click();
                    // labels[selectedIndex].classList.add("answerClick")
                    index++;
                    countdown = timeLeft;
                } else if (index >= elements.length) {
                    btn.textContent = text
                    clearInterval(intervalId); // 遍历完数组后，点击完后停止
                }
            }, 1000);
        }

    } else if (text == "随机排名") {
        // alert("随机排名--进来了")
        let elements = document.querySelectorAll('.ranking.answerRanking'); 
        if (elements && elements.length > 0) {
            let index = 0;
            let countdown = timeLeft;
            let intervalId = setInterval(() => {
                countdown--;
                btn.textContent = "第" + (index + 1) + "/" + elements.length + "在" + countdown + "秒后选中";
                if (index < elements.length && countdown <= 0) {
                    let labels = elements[index].querySelectorAll('.ranking__answers-wrapper .ranking__answer-btn:not(.ranking__answer-btn--disabled)') // [1].click()
                    let selectedIndex = Math.floor(Math.random() * labels.length);
                    labels[selectedIndex].click();
                    index++;
                    countdown = timeLeft;
                } else if (index >= elements.length) {
                    btn.textContent = text
                    clearInterval(intervalId); // 遍历完数组后，点击完后停止
                }
            }, 1000);
        }
        
    } else if (text == "随机多选") {
        // alert("随机多选")
        let elements = document.querySelectorAll('.answer.answer--multi-choice');
        if (elements) {
            // alert("随机多组多选")
            var index = 0;
            const intervalId = setInterval(() => {
                if (index < elements.length) {
                    var labels = elements[index].querySelectorAll('.matrix__answer.answer--single-choice'); // 每组中的（单选）
                    var selectedIndex = Math.floor(Math.random() * labels.length);
                    labels[selectedIndex].click();
                    labels[selectedIndex].classList.add("answerClick")
                    index++;
                } else {
                    clearInterval(intervalId); // 点击完后停止
                }
            }, 3000);
        }
        const totalElements = multiChoiceElements.length;
        const minSelected = 2;
        const maxSelected = Math.ceil(totalElements * 0.8); // 80% of total elements
        const selectedCount = Math.floor(Math.random() * (maxSelected - minSelected + 1)) + minSelected;

        let selectedElements = [];

        // 先删除所有已经选择的
        for (let i = 0; i < totalElements; i++) {
            multiChoiceElements[i].classList.remove("answerClick")

        }

        for (let i = 0; i < selectedCount; i++) {
            let randomIndex = Math.floor(Math.random() * totalElements);
            while (selectedElements.includes(randomIndex)) {
                randomIndex = Math.floor(Math.random() * totalElements);
            }
            selectedElements.push(randomIndex);
            if (randomIndex < totalElements - 1) {
                multiChoiceElements[randomIndex].click();
                multiChoiceElements[randomIndex].classList.add("answerClick")
            }

        }

        // // 设置一个延迟执行的函数
        setTimeout(function () {
            console.log('这段代码将在3秒后执行。');
            document.getElementById("submit-btn").click()
        }, 30000);



    }
}
//////////////////////////////////////////////////////////////// 添加随机按钮 end ////////////////////////////////////////////////////////////////


// // 先删除所有已经选择的
// const multiChoiceElements_checked = document.querySelectorAll('.answer.answer--multi-choice.answerClick');
// if (multiChoiceElements_checked) {
//     for (let i = 0; i < multiChoiceElements_checked.length; i++) {
//         multiChoiceElements_checked[randomIndex].click();
//         multiChoiceElements_checked[i].classList.remove("answerClick")
//     }
// }


//////////////////////////////////////////////////////////////// 添加秒表 end ////////////////////////////////////////////////////////////////